package com.ai.bitcoin.wechat.handler;

import com.ai.bitcoin.jpa.entity.BccBasicInfo;
import com.ai.bitcoin.jpa.entity.BccUserBonusConfig;
import com.ai.bitcoin.jpa.service.BccBasicInfoService;
import com.ai.bitcoin.jpa.service.UserBonusService;
import com.ai.bitcoin.vo.UserEncourageReq;
import com.ai.bitcoin.vo.UserEncourageResponse;
import com.ai.bitcoin.wechat.builder.TextBuilder;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class MsgHandler extends AbstractHandler {
    @Autowired
    UserBonusService userBonusService;
    @Autowired
    BccBasicInfoService bccBasicInfoService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wechatMessage,
                                    Map<String, Object> context, WxMpService wechatService,
                                    WxSessionManager sessionManager) {

        String content = wechatMessage.getContent();
        UserEncourageReq request = new UserEncourageReq();
        request.setOpenId(wechatMessage.getFromUser());
        String eventTypeCd = null;
        if (StringUtils.indexOfAny(StringUtils.lowerCase(content), new String[]{"查看挖矿机制", "我的plc"}) > -1) {
            //可挖PLC信息
            eventTypeCd = "0106";
        }
        else if (StringUtils.equals(content, "签到")) {
            eventTypeCd = "0102";
        }
        else if (StringUtils.indexOfAny(StringUtils.lowerCase(content), "plc", "评链网") > -1) {
            eventTypeCd = "0310";
        }
        else {
            BccBasicInfo bccBasicInfo = bccBasicInfoService.getByKeyword(StringUtils.lowerCase(content));
            if (bccBasicInfo != null) {
                eventTypeCd = "0104";
                request.setBccBasicInfo(bccBasicInfo);
            }
        }
        if (eventTypeCd != null) {
//            request.setOpenId("oaPg603V5oO1fjRZHKQDf_VQ-hBM");
            UserEncourageResponse response = userBonusService.sendBonus(BccUserBonusConfig.EVENT_SOURCE_MP, eventTypeCd, request);
            if (CollectionUtils.isNotEmpty(response.getMessageList())) {
                return new TextBuilder().build(response.getMessageList().get(0), wechatMessage, wechatService);
            }
        }
        return null;

    }

}
